import os
import json
from flask import Flask,url_for
import importlib
import pkgutil
from util.Route import blu
from util.Log import logging
app = Flask('app',static_url_path='/public', static_folder='public')

app.logger.handle = logging.getLogger('falsk.app').handle
app.config["UPLOAD_FOLDER"] = "public"  # 设置上传文件将存储的文件夹
if not os.path.exists(app.config["UPLOAD_FOLDER"]):
    os.makedirs(app.config["UPLOAD_FOLDER"])
    
def my_json_load(json_file):
    if not os.path.exists(json_file):
        return None
    try:
        with open(json_file, 'r', encoding='utf-8') as f:
            json_str = json.dumps(eval(f.read()))
            obj_json = json.loads(json_str)
        if isinstance(obj_json, dict) == False:
            return None
        else:
            return obj_json
    except:
        return None
# 包扫描函数
def pack_scan(packname:list[str]):
    def import_submodules(package):
        """递归导入子模块"""
        for _, module_name, _ in pkgutil.iter_modules(package.__path__):
            importlib.import_module(package.__name__ + '.' + module_name)
    for pk in packname:
        import_submodules(importlib.import_module(pk))
        
# 包扫描扫描路由和拦截器(加载所有路由)
pack_scan(['controller','interceptor'])
app.register_blueprint(blu)
